package test.n00500;


import static utils.Tools.listOf;

public class Problem00590 {
    public static void main(String[] args) {
        println(3);
    }

    public static void println(int n) {
        Solution ss = new Solution();
        System.out.println(listOf(n) + "," + listOf(ss.generateMatrix(n)));
    }

    public static class Solution {

        /**
         * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
         *
         * 解题思路:
         *  模拟
         * @param n
         * @return
         */
        public int[][] generateMatrix(int n) {
            int left = 0, right = n - 1, top = 0, bottom = n - 1;

            int[][] matrix = new int[n][n];
            int num = 0;
            while (left <= right && top <= bottom) {
                for (int col = left; col <= right; col++) {
                    matrix[top][col] = ++num;
                }

                for (int row = top + 1; row <= bottom; row++) {
                    matrix[row][right] = ++num;
                }

                if (left < right && top < bottom) {
                    for(int col = right - 1; col >= left; col--) {
                        matrix[bottom][col] = ++num;
                    }

                    for (int row = bottom - 1; row > top; row--) {
                        matrix[row][left] = ++num;
                    }
                }
                left++;
                right--;
                top ++;
                bottom--;
            }
            return matrix;
        }
    }
}
